import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:my_app_01/api/common.dart';
import 'package:my_app_01/components/MCard.dart';
import 'package:my_app_01/components/MEmpty.dart';
import 'package:my_app_01/components/MShimmer.dart';
import 'package:my_app_01/components/MTitle.dart';
import 'package:my_app_01/pages/common/list.dart';
import 'package:my_app_01/pages/menu/MenuShimmer.dart';
import 'package:my_app_01/service/HttpUtils.dart';
import 'package:my_app_01/utils/index.dart';
import 'package:nil/nil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shimmer/shimmer.dart';

class MenuPage extends StatefulWidget {
  @override
  State<MenuPage> createState() => _MenuPageState();
}

class _MenuPageState extends State<MenuPage> {
  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  List menuList = [];

  List<dynamic>? buildTree(List<dynamic> items) {
    Map<String, dynamic> treeObj = {};
    List<Map<String, dynamic>> list = [];

    for (var item in items) {
      item['children'] = [];
      treeObj[item['id']] = item;
    }

    for (var item in items) {
      var mapItem = treeObj[item['parentid']];
      if (mapItem != null) {
        mapItem['children'].add(item);
      } else if (item['parentid'] == '0') {
        list.add(item);
      }
    }
    return list;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("个人中心"),
        centerTitle: true,
        shadowColor: Colors.black12,
        surfaceTintColor: Colors.white,
        elevation: 6,
      ),
      body: FutureBuilder(
          future: CommonApi.getMenuList(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              EasyLoading.show(status: "加载中...");
              return const MenuShimmer();
            }
            if (snapshot.connectionState == ConnectionState.done) {
              EasyLoading.dismiss();
              if (snapshot.data?['data'] != null) {
                menuList = buildTree(snapshot.data?['data'])!;
              }
              if (menuList.isEmpty) {
                return const MEmpty(message: "暂无菜单数据");
              } else {
                return SmartRefresher(
                  controller: _refreshController,
                  onRefresh: () async {
                    var res = await CommonApi.getMenuList();
                    if (res['status'] == 0) {
                      var list = buildTree(res['data'])!;
                      setState(() {
                        menuList = list;
                      });
                    }
                    _refreshController.loadComplete();
                  },
                  child: ListView(
                    padding: const EdgeInsets.all(20),
                    children: menuList.map((ele) {
                      return ele['children'].length > 0
                          ? Column(
                              children: [
                                MTitle(
                                  icon: IconData(MUtils.generateRandomEHex(5), fontFamily: 'MaterialIcons'),
                                  title: Text("${ele['name']}", style: MCard.defaultTitleStyle),
                                ),
                                Card(
                                    margin: const EdgeInsets.only(top: 15, bottom: 30),
                                    color: Colors.white,
                                    surfaceTintColor: Colors.white,
                                    elevation: 6,
                                    shadowColor: Colors.black38,
                                    clipBehavior: Clip.hardEdge,
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: Container(
                                      padding: const EdgeInsets.all(15),
                                      child: GridView.builder(
                                        physics: const NeverScrollableScrollPhysics(),
                                        shrinkWrap: true,
                                        padding: const EdgeInsets.all(0.0),
                                        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                                            //横轴元素个数
                                            crossAxisCount: 4,
                                            //垂直单个子widget间距
                                            mainAxisSpacing: 8,
                                            //水平单个子widget间距
                                            crossAxisSpacing: 8,
                                            //item宽高比例
                                            childAspectRatio: 1.0),
                                        itemBuilder: (context, index) {
                                          var currentItem = ele['children'].elementAt(index);
                                          return InkWell(
                                            onTap: () async {
                                              var result = await Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                  builder: (context) {
                                                    return ListPage(
                                                      pageTitle: currentItem['name'],
                                                    );
                                                  },
                                                ),
                                              );
                                            },
                                            child: Column(
                                              children: [
                                                Icon(
                                                  IconData(MUtils.generateRandomEHex(5), fontFamily: 'MaterialIcons'),
                                                  size: 32,
                                                  color: Color.fromRGBO(Random().nextInt(256), Random().nextInt(256),
                                                      Random().nextInt(256), 1),
                                                ),
                                                const SizedBox(
                                                  height: 10,
                                                ),
                                                Text(
                                                  "${currentItem['name']}",
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                  style: const TextStyle(
                                                    fontSize: 16,
                                                  ),
                                                )
                                              ],
                                            ),
                                          );
                                        },
                                        itemCount: ele['children'].toList().length,
                                      ),
                                    ))
                              ],
                            )
                          : nil;
                    }).toList(),
                  ),
                );
              }
            }
            return nil;
          }),
    );
  }
}
